import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import { Sequelize, DataTypes, Model } from 'sequelize';

// 创建 Sequelize 实例
const sequelize = new Sequelize(
    'mingcai_db',
    'root',
    'TiRWIsZCwdRXeBxZ',
    {
        host: '95.169.25.181',
        dialect: 'mysql'
    }
);

// 定义图书模型
class Book extends Model {}
Book.init(
    {
        title: {
            type: DataTypes.STRING,
            allowNull: false
        },
        author: {
            type: DataTypes.STRING,
            allowNull: false
        },
        release_date: {
            type: DataTypes.DATEONLY,
        },
        subject: {
            type: DataTypes.INTEGER,
        }
    },
    {
        sequelize,
        modelName: 'books',
        timestamps: true // 禁用自动添加的 createdAt 和 updatedAt 字段
    }
);

// 创建 Koa 应用和路由
const app = new Koa();
const router = new Router();

// 解析请求体
app.use(bodyParser());

// 定义路由
router.get('/books', async (ctx) => {
    const books = await Book.findAll();
    ctx.body = books;
});

// 定义路由
router.get('/p/books', async (ctx) => {
    const books = await Book.findAndCountAll({
        where: {},
        order: [],
        limit: 5,
        offset: 0,
    });
    ctx.body = books;
});

router.post('/books', async (ctx) => {
    // @ts-ignore
    const { title, author, release_date, subject } = ctx.request.body;
    const book = await Book.create({ title, author, release_date, subject });
    ctx.body = book;
});

router.put('/books/:id', async (ctx) => {
    const { id } = ctx.params;
    // @ts-ignore
    const { title, author, release_date, subject } = ctx.request.body;
    const [updated] = await Book.update({ title, author, release_date, subject }, {
        where: { id }
    });
    if (updated) {
        ctx.body = { message: 'Book updated successfully' };
    } else {
        ctx.body = { message: 'Book not found' };
    }
});

router.delete('/books/:id', async (ctx) => {
    const { id } = ctx.params;
    const deleted = await Book.destroy({
        where: { id }
    });
    if (deleted) {
        ctx.body = { message: 'Book deleted successfully' };
    } else {
        ctx.body = { message: 'Book not found' };
    }
});

// 使用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
